package com.example.a02back.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a02back.dto.*;
import com.example.a02back.entity.Trade;
import com.example.a02back.entity.User;
import com.example.a02back.mapper.TradeMapper;
import com.example.a02back.mapper.UserMapper;
import com.example.a02back.service.ITradeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.a02back.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author SimpChaos
 * @since 2022-07-11
 */
@Slf4j
@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade> implements ITradeService {

    @Resource
    private TradeMapper tradeMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * @Description: 
     * @Author: SimpChaos 
     * @Date: 2022/7/15 17:12
     * @Param: [uid, sid, title, info, type, deadline]
     * @Return: java.lang.String
     */
    public String publish(String uid,String sid,String title,String info,Integer type,Integer tradeType,String deadline,Integer price){

        Trade t = new Trade();
        t.setUid(uid);
        t.setTitle(title);
        t.setInfo(info);
        t.setSid(sid);
        t.setDeadline(deadline);
        t.setType(type);
        t.setTradeType(tradeType);
        t.setIsclosed(0);
        t.setIsCancel(0);
        t.setPrice(price);

        
        return String.valueOf(this.save(t));
    }


    public String publishImage(MultipartFile file, String uid, String sid) throws IOException {
        //得到url

        String path = FileUtils.upload(file,uid,sid);
        //if判断是否有过
        LambdaQueryWrapper<Trade> wrapper1 = new LambdaQueryWrapper<>();
        LambdaUpdateWrapper<Trade> wrapper2 = new LambdaUpdateWrapper<>();
        wrapper1.eq(Trade::getSid,sid);
        List<String> l = new ArrayList<>();
        String s = tradeMapper.selectOne(wrapper1).getImage();
        if(s == null){
            l.add(path);

            String jiujiuwo = JSONObject.toJSONString(l);

            wrapper2.eq(Trade::getSid,sid).set(Trade::getImage,jiujiuwo).set(Trade::getImageFirst,path);
            Integer rows = tradeMapper.update(null,wrapper2);
            System.out.print(rows);
            if(rows == 1) return jiujiuwo;
            else return "failed to publish";
        }
        else{
            List<String> LIST = JSONObject.parseArray(s,String.class);
            LIST.add(path);
            String GAOSIWO = JSONObject.toJSONString(LIST);
            wrapper2.eq(Trade::getSid,sid).set(Trade::getImage,GAOSIWO);
            Integer rows = tradeMapper.update(null,wrapper2);
            System.out.print(rows);
            if(rows == 1) return GAOSIWO;
            else return "failed to publish";
        }



        //json转译

    }



/**
 * @Description:
 * @Author: SimpChaos
 * @Date: 2022/7/14 14:56
 * @Param: [rid]
 * @Return: com.example.a02back.dto.TradeDetail
 */
    public TradeDetail getOne(String sid){
        TradeDetail w = new TradeDetail();

        //找到该悬赏令
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Trade::getSid,sid);
        Trade t = tradeMapper.selectOne(wrapper);
        BeanUtil.copyProperties(t,w);
        LambdaUpdateWrapper<User> wrapper1 = new LambdaUpdateWrapper<User>();
        wrapper1.eq(User::getUid,t.getUid());
        User u = userMapper.selectOne(wrapper1);
        w.setUsrName(u.getNickname());
        w.setUsrImg(u.getAvatarUrl());
        w.setImgList(JSONObject.parseArray(t.getImage(),String.class));
        return w;
    }

    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/20 20:52
     * @Param: []
     * @Return: java.util.List<com.example.a02back.dto.littleWantingList>
     */
    public List<littleWantingList> getRedList(){
        Page<Trade> page = new Page<>(1, 4);
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Trade::getTradeType,1).eq(Trade::getIsclosed,0).eq(Trade::getIsCancel,0);
        List<Trade> records = this.page(page,wrapper).getRecords();
        littleWantingList w = new littleWantingList();
        List<littleWantingList> result = new ArrayList<>();
        for(Trade t:records){
            w.setDetail(t.getInfo());
            w.setRedDeadline(t.getDeadline());
            w.setPrice(t.getPrice());
            w.setTitle(t.getTitle());
            w.setSid(t.getSid());
            result.add(w);
        }
        return result;
    }



/**
 * @Description:
 * @Author: SimpChaos
 * @Date: 2022/7/14 15:37
 * @Param: [page]
 * @Return: java.util.List<com.example.a02back.dto.ListDetail>
 */
    public List<ListDetail> getWantList(Long decode){
        Page<Trade> page = new Page<>(decode, 10);
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Trade::getTradeType,1).eq(Trade::getIsclosed,0).eq(Trade::getIsCancel,0);
        return getListDetails(page, wrapper);
    }



    public List<ListDetail> getSellList(Long decode,Integer type){
        Page<Trade> page = new Page<>(decode, 10);
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper();
        if (type == 0){
        wrapper.eq(Trade::getTradeType,2).eq(Trade::getIsclosed,0).eq(Trade::getIsCancel,0);
        }
        else {
            wrapper.eq(Trade::getTradeType, 2).eq(Trade::getIsclosed, 0).eq(Trade::getIsCancel, 0).eq(Trade::getType, type);
        }
        return getListDetails(page, wrapper);
    }

    private List<ListDetail> getListDetails(Page<Trade> page, LambdaQueryWrapper<Trade> wrapper) {
        List<Trade> records = this.page(page,wrapper).getRecords();
        ListDetail w = new ListDetail();
        List<ListDetail> result = new ArrayList<>();
        for(Trade t:records){
            BeanUtil.copyProperties(t,w);
            LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<User>();
            wrapper1.eq(User::getUid,t.getUid());
            User u = userMapper.selectOne(wrapper1);
            w.setUsrName(u.getNickname());
            w.setUsrImg(u.getAvatarUrl());
            result.add(w);
        }
        return result;
    }


/**
 * @Description:
 * @Author: SimpChaos
 * @Date: 2022/7/15 17:43
 * @Param: [uid]
 * @Return: java.util.List<com.example.a02back.dto.MyDone>
 */
    public MyDoneList getMyDone(Long decode, String uid){
        Page<Trade> page = new Page<>(decode, 10);
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Trade> wrapper1 = new LambdaQueryWrapper<>();
        wrapper.eq(Trade::getUid,uid).eq(Trade::getIsclosed,1).eq(Trade::getTradeType,1);
        wrapper1.eq(Trade::getUid,uid).eq(Trade::getIsclosed,1).eq(Trade::getTradeType,2);
        MyDoneList my = new MyDoneList();
        my.setWantList(getMyDoneList(page,wrapper));
        my.setSellList(getMyDoneList(page,wrapper1));
        return my;
    }


/**
 * @Description: 
 * @Author: SimpChaos 
 * @Date: 2022/7/15 17:51
 * @Param: [uid]
 * @Return: java.util.List<com.example.a02back.dto.MyDone>
 */
    public MyDoneList getMyPublish(Long decode,String uid){
        Page<Trade> page = new Page<>(decode, 10);
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Trade> wrapper1 = new LambdaQueryWrapper<>();
        wrapper.eq(Trade::getUid,uid).eq(Trade::getIsclosed,0).eq(Trade::getTradeType,1);
        wrapper1.eq(Trade::getUid,uid).eq(Trade::getIsclosed,0).eq(Trade::getTradeType,2);
        MyDoneList my = new MyDoneList();
        my.setWantList(getMyDoneList(page,wrapper));
        my.setSellList(getMyDoneList(page,wrapper1));
        return my;
    }

    
    /**
     * @Description: 
     * @Author: SimpChaos 
     * @Date: 2022/7/15 17:52
     * @Param: [uid]
     * @Return: java.util.List<com.example.a02back.dto.MyDone>
     */
    public MyDoneList getMyBuy(Long decode,String uid){
        Page<Trade> page = new Page<>(decode, 10);
        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Trade> wrapper1 = new LambdaQueryWrapper<>();
        wrapper.eq(Trade::getSwapper,uid).eq(Trade::getIsclosed,1).eq(Trade::getTradeType,1);
        wrapper1.eq(Trade::getSwapper,uid).eq(Trade::getIsclosed,1).eq(Trade::getTradeType,2);
        MyDoneList my = new MyDoneList();
        my.setWantList(getMyDoneList(page,wrapper));
        my.setSellList(getMyDoneList(page,wrapper1));
        return my;
    }

    public List<MyDone> getMyDoneList(Page<Trade> page, LambdaQueryWrapper<Trade> wrapper){
        List<Trade> records = this.page(page,wrapper).getRecords();
        List<MyDone> List = new ArrayList<>();
        MyDone d = new MyDone();
        for(Trade trade :records){
            BeanUtil.copyProperties(trade,d);
            List.add(d);
        }
        return List;
    }


    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/15 21:55
     * @Param: [list]
     * @Return: java.util.List<com.example.a02back.dto.MyDone>
     */
    public List<MyDone> getFavItemList(List<String> list,Integer type){
        List<MyDone> list1 = new ArrayList<>();
        LambdaQueryWrapper<Trade> wrapper  = new LambdaQueryWrapper<>();
        MyDone my = new MyDone();
        for(String s:list){
            wrapper.eq(Trade::getSid,s).eq(Trade::getTradeType,type);
            Trade t = this.getOne(wrapper);
            if(!(t == null))
            {
            BeanUtil.copyProperties(t,my);
            list1.add(my);
            }
        }
        return list1;
    }



    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/16 1:40
     * @Param: [sid, title, info, type, deadline, price]
     * @Return: java.lang.String
     */
    public String update(String sid,String title,String info,Integer type,String deadline,Integer price){
        Trade t = this.getById(sid);
        t.setTitle(title);
        t.setInfo(info);
        t.setSid(sid);
        t.setDeadline(deadline);
        t.setTradeType(type);
        t.setIsclosed(0);
        t.setIsCancel(0);
        t.setPrice(price);

        return String.valueOf(this.updateById(t));
    }

    public String updateImg(MultipartFile file,Integer number,String uid,String sid) throws IOException {
        String path = FileUtils.upload(file,uid,sid);
        List<String> imgList = JSONObject.parseArray(this.getById(sid).getImage(),String.class);
        //从0开始
        imgList.set(number-1,path);
        String newList = JSONObject.toJSONString(imgList);
        LambdaUpdateWrapper<Trade> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Trade::getSid,sid).set(Trade::getImage,newList);
        return String.valueOf(this.update(wrapper));
    }




    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/16 1:42
     * @Param: [sid]
     * @Return: java.lang.String
     */
    public String delete(String sid){
        LambdaUpdateWrapper<Trade> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Trade::getSid,sid).set(Trade::getIsCancel,1);
        return String.valueOf(this.update(wrapper));
    }


    /**
     * @Description: 
     * @Author: SimpChaos 
     * @Date: 2022/7/20 15:51
     * @Param: [swapper, sid]
     * @Return: java.lang.String
     */
    public String accepcTrade(String swapper,String sid){
        Trade t = this.getById(sid);
        t.setSwapper(swapper);
        t.setIsclosed(1);
        LambdaUpdateWrapper<Trade> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Trade::getSid,sid).set(Trade::getSwapper,swapper).set(Trade::getIsclosed,1);
        return String.valueOf(this.update(wrapper));
    }


    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/20 15:51
     * @Param: [swapper, sid]
     * @Return: java.lang.String
     */
    public String finishTrade(String sid){
        Trade t = this.getById(sid);
        t.setIsclosed(2);
        LambdaUpdateWrapper<Trade> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Trade::getSid,sid).set(Trade::getIsclosed,2);
        return String.valueOf(this.update(wrapper));
    }

    public String cancelTrade(String sid){
        Trade t = this.getById(sid);
        t.setSwapper(null);
        t.setIsclosed(0);
        LambdaUpdateWrapper<Trade> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Trade::getSid,sid).set(Trade::getSwapper,null).set(Trade::getIsclosed,0);
        return String.valueOf(this.update(wrapper));

    }

    public List<Trade> searchByKeyword(String keyword){

        LambdaQueryWrapper<Trade> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Trade::getTitle,keyword).or().like(Trade::getInfo,keyword).eq(Trade::getTradeType,2);
        return this.list(wrapper);


    }

    

}
